package two;

public class A031 {


    //k个一组翻转链表
    public ListNode reverse(ListNode head) {
        if(head==null || head.next==null) return head;
        ListNode newHead = new ListNode();
        ListNode cur = head;
        while(cur!=null) {
            ListNode next = cur.next;
            cur.next = newHead.next;
            newHead.next = cur;
            cur = next;
        }
        return newHead.next;
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode newHead = new ListNode();
        ListNode prev = head;
        ListNode tail = head;
        ListNode cur = newHead;
        while(head!=null) {
            prev=head;
            //1.定位需要翻转的两头
            for(int i=0;i<k-1;i++) {
                if(head==null) break;
                head = head.next;
            }
            tail=head;
            if(tail!=null) {
                head=tail.next;
                tail.next=null;
                //2.翻转
                cur.next = reverse(prev);
                cur=prev;
            }else {
                cur.next=prev;

                break;
            }
        }
        return newHead.next;
    }
}
